//
//  NRWCarFirstInspectionVC.m
//  New_Runway
//
//  Created by 邢毅 on 2018/4/20.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarFirstInspectionVC.h"
#import "NRWCarSearchView.h"
#import "NRWCarInspectionCell.h"
#import "NRWCarListsModel.h"
#import "UIAlertController+Extend.h"
#import "PickCustomView.h"
#import "NRWCarAlterView.h"

@interface NRWCarFirstInspectionVC ()
<NRWCarSearchViewDelegate,
NRWCarInspectionCellDelegate,
UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate,
CustomPickViewDelegate,
NRWCarAlterViewDelegate>

@end

@implementation NRWCarFirstInspectionVC
{
    UITableView *_tableView;
    NSInteger _pageIndex;
    NRWCarListsModel *_model;
    NSInteger _lastCheckIndex;
    NRWCarSearchView *_searchView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    if (!self.isSearch) {
        [self loadNewDataWithSize:15];
    }
}

- (void)setupUI {
    
    [self setupSearchBar];
    
    [self setupTableView];
}

- (void)setupSearchBar {
    
    _searchView = [[NRWCarSearchView alloc] initWithPlaceHold:@"请输入VIN码后六位进行查询" leftImageName:@"icon_search_vin" rightImageName:@"icon_delete_vin"];
    _searchView.delegate_custom = self;
    _searchView.delegate = self;
    self.navigationBarView.addSubview(_searchView);
    
    if (self.isSearch) {
        [_searchView becomeFirstResponder];
    }
    
    _searchView.layer.cornerRadius = 13;
    _searchView.layer.masksToBounds = YES;
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBarView.mas_left).offset(62);
        make.right.equalTo(self.navigationBarView.mas_right).offset(-62);
        make.height.equalTo(@27);
        make.bottom.equalTo(self.navigationBarView.mas_bottom).offset(-8);
    }];
}

- (void)setupTableView {
    
    _tableView = DPTableViewForStyle(UITableViewStylePlain)
    .setDelegate(self)
    .setDataSource(self)
    .registerCell(NRWCarInspectionCell.class, @"cell")
    .setTableFooterView(DPView())
    .setFrame(CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH));
    
    [_tableView addHeaderRefreshWithTarget:self action:@selector(loadNewData)];
    [_tableView addFooterRefreshWithTarget:self action:@selector(loadMoreData)];
    
    self.view.addSubview(_tableView);
}

#pragma mark - network
- (void)refreshData {
    
    [self loadNewDataWithSize:_pageIndex * 15];
}

- (void)loadNewData {
    
    [self loadNewDataWithSize:15];
}

- (void)loadNewDataWithSize:(NSInteger)size {
    
    _pageIndex = 1;
    [self loadDataWithSize:size];
}

- (void)loadMoreData {
    
    _pageIndex++;
    [self loadDataWithSize:15];
}

- (void)loadDataWithSize:(NSInteger)size {
    
    if (size == 0) {
        size = 15;
    }
    
    NSMutableDictionary *dictM = @{}.mutableCopy;
    if ([NRWCarUser sharedUser].marketId == nil) {
        [ShowMessage showHintMessage:@"markterId不能为空" duration:1 withRemindId:remindWarning];
        return;
    } else {
        [dictM setObject:[NRWCarUser sharedUser].marketId forKey:@"marketId"];
    }
    
    if (_searchView.text.length > 0) {
        [dictM setObject:_searchView.text forKey:@"carVin6"];
    }
    
    [dictM setObject:@(_pageIndex) forKey:@"pageIndex"];
    [dictM setObject:@(size) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", Api, getCarFirstDetectList];
   
    [SVProgressHUD show];
    
    [YQNetworking postWithUrl:url refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        
        [_tableView endRefresh];
        [SVProgressHUD dismiss];
        
        NRWCarListsModel *model = [NRWCarListsModel mj_objectWithKeyValues:response];
        
        if (_pageIndex == 1) {
            
            if (model.result.count == 0) {
                [_tableView addDefaultViewWithText:@"无相关检索车辆" defaultImageType:DefaultImageTypeNoData];
            } else {
                [_tableView removeDefaultView];
            }
            _model = model;
        } else {
            
            if (model.result.count == 0) { return; }
            NSMutableArray *arrM = [NSMutableArray arrayWithArray:_model.result];
            [arrM addObjectsFromArray:model.result];
            _model.result = arrM.copy;
        }
        [_tableView reloadData];
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [_tableView endRefresh];
        [SVProgressHUD dismiss];
    }];
}

- (void)updateCarStateWithCarId:(NSString *)carId content:(NSString *)content stateValue:(NSString *)stateValue {
    
    NSMutableDictionary *dictM = @{}.mutableCopy;
    
    if (carId.length) {
        [dictM setObject:carId forKey:@"carId"];
    } else {
        [ShowMessage showHintMessage:@"carId不能为空" duration:1 withRemindId:remindWarning];
        return;
    }
    
    if (stateValue.length) {
        [dictM setObject:stateValue forKey:@"stateValue"];
    } else {
        [ShowMessage showHintMessage:@"stateValue不能为空" duration:1 withRemindId:remindWarning];
        return;
    }
    
    if ([NRWCarUser sharedUser].userId.length) {
        [dictM setObject:[NRWCarUser sharedUser].userId forKey:@"userId"];
    } else {
        [ShowMessage showHintMessage:@"stateValue不能为空" duration:1 withRemindId:remindWarning];
        return;
    }
    
    if (content.length) {
        [dictM setObject:content forKey:@"content"];
    }
    
    [dictM setObject:@"carDetectState" forKey:@"stateKey"];
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@", Api, updateCarState] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        
        if ([response[@"code"] integerValue] == 1) {
            
            [ShowMessage showHintMessage:@"操作成功" duration:1 withRemindId:remindSuccess];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self loadNewDataWithSize:_pageIndex * 15];
            });
            
        } else {
            
            [ShowMessage showHintMessage:@"操作失败, 请稍后再试" duration:1 withRemindId:remindSuccess];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
}

#pragma mark - tableViewDelegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _model.result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarInspectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    Result *result = _model.result[indexPath.row];
    
    cell.carTitle = result.carTitle;
    cell.detailString = [NSString stringWithFormat:@"%@/%@/%@", result.carMileageString, result.carLicenceDateString, result.shop.shopName];
    cell.carVinString = [NSString stringWithFormat:@"车架号: %@", result.carVin];
    cell.timeString = [NSString stringWithFormat:@"%@", result.carCreateTimeString];
    cell.carImage = result.carImageUrl;
    cell.carOrderState = result.carOrderState;
    cell.carAuthState = result.carAuthState;
    cell.tag = indexPath.row;
    cell.delegate = self;
    [cell setCarDetectState:result.carDetectState andCarStockState:result.carStockState];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 110;
}

#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (self.isSearch) {
        return YES;
    } else {
        NRWCarFirstInspectionVC *vc = [[NRWCarFirstInspectionVC alloc] init];
        vc.isSearch = YES;
        [self.navigationController pushViewController:vc animated:NO];
        return NO;
    }
}

- (void)searchView:(NRWCarSearchView *)searchView rightBtnDidClick:(UIButton *)sender {
    
    [self reloadFirstPageData];
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)searchView:(NRWCarSearchView *)searchView textDidChange:(NSString *)text {
    
    if (searchView.text.length > 6) {
        searchView.text = [searchView.text substringToIndex:6];
    }
    
    searchView.text = [searchView.text uppercaseString];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (string.length == 0) {
        return YES;
    }
    
    return [NRWCarRegularTool isValidateByRegex:@"[a-h|j-n|p|r-z|A-H|J-N|P|R-Z|0-9]" text:string];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (_searchView.text.length == 6) {
        
        [self loadNewDataWithSize:15];
        [_searchView resignFirstResponder];
        return YES;
    } else {
        [ShowMessage showHintMessage:@"请输入VIN后六位" duration:1 withRemindId:remindWarning];
        return NO;
    }
}

#pragma mark - cellDelegate
- (void)carInspectionCell:(NRWCarInspectionCell *)cell checkBtnDidClick:(UIButton *)sender {
    
    _lastCheckIndex = sender.tag;
    
    NRWCarAlterView *alterView = [NRWCarAlterView alterViewWithTitle:@"初检是否通过" messgae:nil leftTitle:@"通过" rightTitle:@"不通过" showCloseBtn:YES delegate:self];
    alterView.rightBtnTitleColor = [UIColor redColor];
    [alterView show];
    return;
}

#pragma mark - NRWCarAlterViewDelegate
- (void)alterView:(NRWCarAlterView *)alter didClickWithType:(NRWCarAlterViewButtonType)type btnTitle:(NSString *)title {
    
    if (type == kAlterViewButtonTypeLeft) {
        [self updateCarStateWithCarId:_model.result[_lastCheckIndex].carId content:nil stateValue:@"520"];
    } else {
        [self showContentPick];
    }
}

#pragma mark - PickCustomViewDelegate
- (void)customPickView:(PickCustomView *)customPickView selectedTitle:(NSString *)selectedTitle index:(NSInteger)index {
    
    [self updateCarStateWithCarId:_model.result[_lastCheckIndex].carId content:selectedTitle stateValue:@"510"];
}

#pragma mark - private
- (void)showContentPick {
    
    PickCustomView *pickView = [[PickCustomView alloc] init];
    pickView.pickerViewHeight = 300;
    pickView.dataArray = @[@"事故车", @"水泡车", @"火烧车"].mutableCopy;
    pickView.delegate = self;
    [pickView show];
}

- (void)reloadFirstPageData {
    
    NRWCarFirstInspectionVC *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
    
    if ([vc isKindOfClass:[self class]]) {
        
        [vc refreshData];
    }
}

- (void)leftItemClick {
    
    [self reloadFirstPageData];
    
    [self.navigationController popViewControllerAnimated:!self.isSearch];
}

@end
